/**
 * Created by woziji00226 on 2024-12-13 10:21:21.
 * 倒计时器
 * 一毫秒进1
 */
class ColorDemon_Countdown_W26 extends EventDispatcher {
    //完成倒计时
    public static EVENT_COUNTDOWN_COMPLETED = 'EVENT_COUNTDOWN_COMPLETED';
    //倒计时改变时触发
    public static EVENT_CURRENT_COUNTDOWN_CHANGE = 'EVENT_CURRENT_COUNTDOWN_CHANGE';

    //倒计时 
    private _countdown = 0;

    private _currentCount = 0;

    private _currentTimeMS = 0;//当前时间，毫秒

    //正在运行
    private _playing = false;

    
    constructor(countdown: number) {
        super();
        this._countdown = countdown;
    }

    private _onUpdate() {
        if (!this._playing) {
            return;
        }

        //@ts-ignore
        var f = (Laya.timer.delta / 1000);
        this.currentCount -= f * 1000;

        if (this.currentCount <= 0) {
            this.currentCount = 0;
            this.complete();
            os.remove_ENTERFRAME(this._onUpdate, this);
        }
    }

    /**
     * 开始
     */
    public start() {
        this._playing = true;
        this.currentCount = this._countdown;
        this._currentTimeMS = Date.now();
        os.remove_ENTERFRAME(this._onUpdate, this);
        os.add_ENTERFRAME(this._onUpdate, this);
    }


    /**
     * 完成
     */
    public complete() {
        this._playing = false;
        this.event(ColorDemon_Countdown_W26.EVENT_COUNTDOWN_COMPLETED);
        os.remove_ENTERFRAME(this._onUpdate, this);
    }

    /**
     * 暂停
     */
    public pause() {
        this._playing = false;
        os.remove_ENTERFRAME(this._onUpdate, this);
    }

    /**
     * 从暂停中继续
     */
    public continue() {
        this._playing = true;
        os.remove_ENTERFRAME(this._onUpdate, this);
        os.add_ENTERFRAME(this._onUpdate, this);
    }

    /**
     * 清理
     */
    public clear() {
        this._playing = false;
        os.remove_ENTERFRAME(this._onUpdate, this);
    }

    /**
     * 在运行状态
     */
    public get playing() {
        return this._playing;
    }

    /**
     * 设置当前倒计时
     * @param value 
     */
    public set currentCount(value: number) {
        this._currentCount = value;
        this.event(ColorDemon_Countdown_W26.EVENT_CURRENT_COUNTDOWN_CHANGE, [this.currentCount]);
    }

    /**
     * 获取倒计时
     */
    public get currentCount() {
        return this._currentCount;
    }
}